<template>
    <div class="client_form_container">
        <el-tabs v-model="activeName" @tab-click="handleClickTabs">
            <el-tab-pane label="基本资料" name="first" class="first">
                <el-form ref="clientForm" :model="formData" :rules="rules" label-width="120px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="分组" prop="parent_sid">
                                <tree-select v-model="formData.parent_sid" v-bind.sync="treeSelectOption"
                                             @input="selectTree" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="类型" prop="rec_type">
                                <el-select v-model="formData.rec_type" placeholder="请选择"
                                           style="margin-right: 5px;width: 100%;" >
                                    <el-option v-for="(item, index) in validRecTypeList"
                                               :key="index" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="编码" prop="code">
                                <el-input v-model="formData.code" autocomplete="off" clearable
                                          placeholder="系统自动生成编号，可手动输入"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="名称" prop="name">
                                <el-input v-model="formData.name" autocomplete="off" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="简称" prop="short_name">
                                <el-input v-model="formData.short_name" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="助记码" prop="search_code">
                                <el-input v-model="formData.search_code" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="主体类型" prop="entity_kind" clearable>
                                <el-radio v-model="formData.entity_kind" :label="1">自然人</el-radio>
                                <el-radio v-model="formData.entity_kind" :label="2">法人</el-radio>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="formData.entity_kind === 1?'身份证号码':'社会信用代码'">
                                <el-input v-model="formData.license_no" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-show="formData.entity_kind === 2">
                            <el-form-item label="法人代表">
                                <el-input v-model="formData.legal_person" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="电话">
                                <el-input v-model="formData.phone" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="开户银行">
                                <el-input v-model="formData.bank_name" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="银行账号">
                                <el-input v-model="formData.bank_account_no" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="银行开户名">
                                <el-input v-model="formData.bank_user_name" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="地址">
                                <el-input v-model="formData.address" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="等级">
                                <el-input v-model="formData.level_id" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系人">
                                <el-input v-model="formData.linker_name" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系电话">
                                <el-input v-model="formData.linker_mobile" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系邮箱">
                                <el-input v-model="formData.linker_email" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24" style="text-align: right;padding-right: 3em;">
                            <div style='display: flex;align-items: center;justify-content: flex-end;gap: 10px;'>
                                <el-button class="btn" @click="handleClose()">关 闭</el-button>
                                <el-button class="btn" type="primary" @click="confirmNew()" v-if='isNew' v-btnLoading>保存并继续新增</el-button>
                                <el-button class="btn" type="primary" @click="confirm(true)" v-btnLoading>确 定</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
                <!-- 监听高度变化 -->
                <resize-sensor initial @resize="handleResizeEvent" />
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import ResizeSensor from 'vue-resize-sensor'

export default {
    name: "ClientForm",
    props: {
        propsData: {
            type: Object,
            default() {
                return {
                    init: true,
                };
            },
        },
        selectBottom: {
            type: Boolean,
            default: false,
        },
        type: {
            type: String,
            default: null,
        },
    },
    components: {
        ResizeSensor,
    },
    data() {
        return {
            activeName: 'first',
            height: 0,
            recTypeList: [
                { label: '客户', value: 1 },
                { label: '供应商', value: 2 },
                { label: '客户/供应商', value: 3 },
            ],
            rules: {
                parent_sid: [
                    { required: false, message: "请选择分组", trigger: "change" },
                ],
                rec_type: [
                    { required: true, message: "请选择类型", trigger: "change" },
                ],
                short_name: [],
                name: [
                    { required: true, message: "请输入名称", trigger: "blur" },
                    //目前只兼容中文、大小写英文、数字
                    {
                        // pattern: /^[A-Za-z0-9\u4e00-\u9fa5]{1,50}$/,
                        // message:
                        //   "最大 50 位大小写英文、数字或者其它地区语言字符，不能包含特殊字符",
                        max: 50,
                        message: "最大 50 位字符，内容过长，请删减",
                        trigger: "blur",
                    },
                ],
            },
            treeSelectOption: {
                defaultExpandLevel: -1,
                clearable: false,
                zIndex: 999999,
                appendToBody: true,
                options: [],
            },
            oldCode: '',
            formData: {},
            contractPersonList: [],
            bizOfficeList: [],
            activeBizOffice: {},
            invoiceData: {},
        };
    },
    computed: {
        tabContainerStyle() {
            return {
                minHeight: `${ this.height }px`,
            };
        },
        cardContainerStyle() {
            let height = $(this.getActiveTabsContainer()).height() * 0.9 - 178;
            return {
                maxHeight: `${ height }px`,
            };
        },
        isNew() {
            if (this.selectBottom) {
                return false
            }
            return this.propsData.row && this.$utils.isEmpty(this.propsData.row.sid)
        },
        validRecTypeList() {
            let recTypeList = this.recTypeList.map(item => $.extend({}, item));
            if (this.type) {
                if (this.type === 'clientsDrawer') {
                    recTypeList = recTypeList.filter(item => [1, 3].includes(item.value));
                } else {
                    recTypeList = recTypeList.filter(item => [2, 3].includes(item.value));
                }
            }
            return recTypeList;
        },
    },
    watch: {
        propsData: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        handleResizeEvent(e) {
            this.height = e.height;
        },
        async init() {
            const _this = this;
            if (_this.propsData.init) {
                return;
            }
            _this.activeName = 'first';
            if (_this.$refs.clientForm) {
                _this.$refs.clientForm.clearValidate();
            }
            _this.formData = $.extend({}, { entity_kind: 2 }, _this.propsData.row);
            if (_this.$utils.isEmpty(_this.formData.parent_sid)) {
                _this.formData = $.extend({}, _this.formData, {
                    parent_sid: '-1',
                });
            }
            _this.initTreeList();
            if (!_this.$utils.isNotEmpty(_this.formData.sid)) {
                _this.generateCode();
            }
        },
        initTreeList() {
            const _this = this;
            if (_this.$utils.isNotEmptyList(_this.propsData.treeList)) {
                let options = _this.transferTreeData(_this.propsData.treeList);
                _this.treeSelectOption = $.extend({}, _this.treeSelectOption, {
                    options,
                    value: _this.formData.parent_sid,
                });
                return;
            }
            _this.fetchData(_this.$api.API_FindBaseRelatedPartyTypeTree).then(result => {
                let options = _this.transferTreeData(result.data);
                _this.treeSelectOption = $.extend({}, _this.treeSelectOption, {
                    options,
                    value: _this.formData.parent_sid,
                });
            }).catch(() => {
            });
        },
        transferTreeData(datas) {
            const _this = this;
            let list = [];
            if (_this.$utils.isNotEmptyList(datas)) {
                list = datas.map(item => {
                    let obj = {};
                    obj.id = item.sid;
                    obj.label = item.name;
                    obj.isDefaultExpanded = true;
                    if (_this.$utils.isNotEmptyList(item.children)) {
                        obj.children = _this.transferTreeData(item.children);
                    }
                    return obj;
                });
            }
            return list;
        },
        selectTree(value) {
            this.formData = $.extend({}, this.formData, {
                parent_sid: value,
            });
            if (this.$refs.clientForm) {
                this.$refs.clientForm.clearValidate('parent_sid');
            }
        },
        generateCode() {
            const _this = this;
            return _this.fetchData(_this.$api.API_GetAutoOrderCode, {
                rule_code: 'base_related_party',
            }).then(result => {
                _this.oldCode = result.data;
                _this.formData = $.extend({}, _this.formData, {
                    code: result.data,
                });
            }).catch(() => {
            });
        },
        handleClickTabs(tab) {
            const _this = this;
            if (tab.name === 'first') {
                return;
            }
            if (_this.$utils.isNotEmpty(_this.formData.sid)) {
                return;
            }
            _this.$confirm("请先保存基本资料", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                showCancelButton: false,
            }).then(() => {
                _this.$set(_this, 'activeName', 'first');
                _this.$forceUpdate();
            }).catch(() => {
            });
        },
        handleClose() {
            this.$emit('event', 'closeDialog');
        },
        async confirm(closeDialog) {
            const _this = this;
            let valid = await _this.validateForm('clientForm');
            if (valid) {
                let subData = $.extend({}, _this.formData);
                return _this.fetchData(_this.$api.API_SaveBaseRelatedParty, subData).then(result => {
                    _this.formData = result.data || {};
                    _this.$message.success('保存成功！');
                    _this.$emit('event', { type: 'refresh', data: _this.formData });
                    if (closeDialog) {
                        _this.$emit('event', 'closeDialog');
                    }
                    return true;
                }).catch(() => {
                    return false;
                });
            }
            return valid;
        },
        async confirmNew() {
            const _this = this;
            await this.confirm();
            _this.formData = $.extend({}, {
                client_kind: '1',
                parent_sid: _this.formData.parent_sid,
                rec_type: _this.formData.rec_type,
                entity_kind: _this.formData.entity_kind,
            });
            _this.generateCode();
            if (_this.$refs.nameInput) {
                _this.$refs.nameInput.focus();
            }
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.client_form_container {
    width: 100%;
    height: 100%;
    overflow: hidden;

    .btn {
        width: 96px;
        height: 36px;

        &.mr3 {
            margin-right: 3em;
        }
    }

    /deep/ .tab_container {
        .item_add {
            cursor: pointer;

            .add_card {
                .el-card__body {
                    display: flex;
                    align-items: center;
                    flex-direction: column;
                }
            }
        }

        .contract_card_container {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            width: 100%;
            overflow-y: auto;
        }

        .el-row {
            height: 100%;

            .el-col {
                height: 100%;

                .card_container {
                    display: flex;
                    justify-content: space-between;
                    flex-wrap: wrap;
                    width: 100%;
                    overflow-y: auto;
                }
            }
        }
    }
}
</style>
